﻿namespace Jhong.FunMVCBlog.Core.Infrastructure
{
    using System;
    using System.IO;
    using System.Text;

    public static class CypticExtension
    {
        public static string GetMD5(this string str)
        {
            byte[] pasArray = System.Text.Encoding.Default.GetBytes(str);
            pasArray = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(pasArray);
            string rMd5Str = "";
            foreach (byte ibyte in pasArray)
                rMd5Str += ibyte.ToString("x").PadLeft(2, '0');
            return rMd5Str;
        }

        public static string EncryptToken(this string str)
        {
            var random = new Random();
            var buffer = Encoding.UTF8.GetBytes(string.Format("{0}{1}", random.Next(9), str));
            var encrptStr = Convert.ToBase64String(buffer);
            return string.Format("{0}{1}", encrptStr.GetMD5(), encrptStr);
        }

        public static bool DecryptToken(this string str, out string output)
        {
            var signKey = str.Substring(0, 32);
            var encrptStr = str.Substring(32);
            output = string.Empty;
            if (false == encrptStr.GetMD5().Equals(signKey)) return false;
            try
            {
                var buffer = Convert.FromBase64String(encrptStr);
                output = Encoding.UTF8.GetString(buffer).Substring(1);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static string GetMD5HashFromFile(this string fileName)
        {
            FileStream file = new FileStream(fileName, FileMode.Open);
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(file);
            file.Close();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
    }
}